//var BASE_URL = 'http://dev.dondereciclo.org//greentomato/dr-app/';
var BASE_URL = 'http://'+window.location.host+'/apps/';
var POINTS_IMAGES = BASE_URL+'resources/img/markers/';
var appMakersManager;

function Category () {
    this.id = new Number()
    this.markers = new Array ();
    this.texto = new String ();
    this.categoria = new String ();
}

var controls = {
    categoryListContainer: document.createElement('div'),
    detailsContainer: document.createElement('div')
};

function Categories () {
    this.defs = {
	categoryListContainer: document.createElement('div'),
	detailsContainer: document.createElement('div')
    }
    this.isLoad = false;
    this.list = [];
    this.load = function () {
	var self = this;
	$.ajax({
	    url: BASE_URL+'php/controllers/categoria.controller.php',
	    success: function (data) {
		var cat = {}, i;
                for (var n=0, l=INIT.length; n<l; n++) {
                    i = INIT[n];
                    cat = new Category ();
		    cat.id = data['categorias'][i]['id'];
		    cat.texto = data['categorias'][i]['nombre'];
		    cat.categoria = data['categorias'][i]['identificador'];
		    self.list[data['categorias'][i]['id']] = cat;
                }
		self.isLoad = true;
		$(document).ready(function () {
		    appMap = new MapController();
		    appMap.init();
		})
	    }
	})
    }
}

var appCategories = new Categories();
appCategories.load();

//MAP CONTROLLER
function MapController () {
    this.map = null;
    this.defs = {
	center: new google.maps.LatLng(-34.603526, -58.381586),
	container:'mapa-content'
    }
    this.options = {
	zoom: 13,
	mapTypeId: google.maps.MapTypeId.ROADMAP,
	disableDefaultUI: true,
	zoomControl: true,
        scrollwheel: false,
	zoomControlOptions: {
	    style: google.maps.ZoomControlStyle.SMALL
	}
    }
    this.init = function () {
	this.map = new google.maps.Map(document.getElementById(this.defs.container), this.options);
	this.map.setCenter(this.defs.center);
	GT_Geolocation.localize(this.map);
	var appSliderBox = new SliderBox();
	appSliderBox.create();

	controls.categoryListContainer.index = -500;
	controls.detailsContainer.index = -500;
	this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(controls.categoryListContainer);
	this.map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controls.detailsContainer);

	appMakersManager = new MarkersManager (appSliderBox);
	appMakersManager.load(INIT[0]);
    }
}
//FIN MAP CONTROLLER

//MARKERS MANAGER
function MarkersManager (appSliderBox) {
    this.defs = {
	infomarkerTpl: document.getElementById('infomarkerTpl').value,
	detailsContaier: false
    }
    this.load = function (catgoriaId) {
	var self = this;
	var appInfobox = new InfoboxManager();
	$.ajax({
	    type:'GET',
	    data: 'categoriaId='+catgoriaId,
	    url:BASE_URL+'php/controllers/marker.controller.php',
	    success:function (xml) {
		var punto;
		$(xml).find('marker').each(function() {
		    punto = new google.maps.LatLng(
			parseFloat($(this).attr("lat")),
			parseFloat($(this).attr("lng"))
			);
		    var marker = new google.maps.Marker({
			map: appMap.map,
			position: punto,
			icon: POINTS_IMAGES+$(this).attr('imagen')+'.png',
			shadow: POINTS_IMAGES+'sombra.png',
			id:$(this).attr('id'),
			nombreUrl: $(this).attr('nombreUrl'),
			nombre: $(this).attr('nombre'),
			direccion: $(this).attr('direccion'),
			imagen: $(this).attr('imagen'),
			categoriasToString: $(this).attr('categoriasToString')
		    });
		    appCategories.list[catgoriaId].markers.push(marker);
		    appInfobox.bindMarker(appMap.map, marker);
		    self.bindMarker(marker);
		})
		punto=null;
	    }
	})
    }
    this.mostrarMarkers = function (categoriaId) {
	var self = this;
	if (appCategories.list[categoriaId].markers.length) {
	    for (n in appCategories.list[categoriaId].markers) {
		appCategories.list[categoriaId].markers[n].setMap(appMap.map);
	    }
	} else {
	    self.load(categoriaId);
	}
    }
    this.ocultarMarkers = function (categoriaId) {
	if (appCategories.list[categoriaId].markers.length) {
	    for (n in appCategories.list[categoriaId].markers) {
		appCategories.list[categoriaId].markers[n].setMap(null);
	    }
	} else {
	    self.load(categoriaId);
	}
    },
    this.mostrarDetalles = function (marker) {
	var self = this;
	if (!self.defs.detailsContaier) {
	    self.defs.detailsContaier = document.getElementById('marker-details-content');
	}
	$.ajax({
	    url:BASE_URL+'php/controllers/infomarker.controller.php?id='+marker.id,
	    data:{
		id:marker.id
	    },
	    type:'post',
	    beforeSend:function () {
		self.defs.detailsContaier.innerHTML = '\
                    <div class="medium-loader" style="width:100%; min-height:430px">\
                        <div class="circle-container rad-border">\
                            <div class="circle-loader rad-border"></div>\
                            <div class="circle-content rad-border"></div>\
                            <div class="center-circle-image rad-border"></div>\
                        </div>\
                    </div>\
                ';
	    },
	    success:function (data) {
		var tpl = self.defs.infomarkerTpl.replace('${classyCategories}', self.classyCategories(data.categoriasToIds));
		var replacer = new Replacer();
		var html = replacer.itemReplace(tpl, data);
		self.defs.detailsContaier.innerHTML = html;
		appSliderBox.scrollEvents('marker-details-content');
                if (data.comentario == "") $('#description-item').remove();
                if (data.direccion == "") $('#address-item').remove();
                if (data.email == "") $('#email-item').remove();
                if (data.horario == "") $('#hour-item').remove();
                if (data.telefono == "") $('#phone-item').remove();
	    }
	})
    }
    this.bindMarker = function (marker) {
	var self = this;
	google.maps.event.addListener(marker, 'click', function() {
	    if (!$('#marker-details-content').hasClass('active')) {
		appSliderBox.moving(controls.detailsContainer, 'det');
	    }
	    self.mostrarDetalles(marker)
	})
    }
    this.classyCategories = function (c) {
	c = c.split(',');
	var html = '';
	for (var i=0, l=c.length; i<l; i++) {
            if (INIT.indexOf(c[i]*1) != -1) {
                html += '<em class="recive-item '+appCategories.list[c[i]].categoria+'-item"><span class="bg-color"></span><span class="val">'+appCategories.list[c[i]].texto+'</span></em>';
            }
	}
	return html;
    }
}
//FIN MARKERS MANAGER

//SLIDER BOX
function SliderBox () {
    this.defs = {
	btn: document.createElement('input'),
	btnDetails: document.createElement('input'),
	isOpen: true
    }
    this.create = function () {
	controls.categoryListContainer.id = 'category-list-container';
	controls.categoryListContainer.className = 'category-list-container border-left overflow active';
	controls.categoryListContainer.style.marginLeft = '0px'
	controls.categoryListContainer.innerHTML = '\
            <div class="scrollear">\
                <span class="border-width bg-color-07"></span>\
                <ul id="category-list" class="category-list box-list first-level">'+this.createItems()+'</ul>\
            </div>\
        ';

	this.defs.btn.id = 'btn-expand-markers-list';
	this.defs.btn.type = 'button';
	controls.categoryListContainer.appendChild(this.defs.btn);

	controls.detailsContainer.id = 'marker-details-content';
	controls.detailsContainer.className = 'overflow';
	controls.detailsContainer.innerHTML = '\
            <div class="scrollear">\n\
                <div class="content">\
                    <div id="datos-row" class="span">\
                        <h3 class="title">Seleccione un punto en el mapa para ver la informaci&oacute;n del punto</h3>\
                    </div>\
                </div>\
            </div>';

	this.defs.btnDetails.id = 'btn-expand-markers-details';
	this.defs.btnDetails.type = 'button';
	controls.detailsContainer.appendChild(this.defs.btnDetails);
	this.bind();
    }
    this.bind = function () {
	var self = this;
	$('#btn-expand-markers-list').live('click', function(){
	    self.moving(controls.categoryListContainer, 'cat');
	});
	$('#btn-expand-markers-details').live('click', function(){
	    self.moving(controls.detailsContainer, 'det');
	});
	/*if($(window).width() < 767) {
	    $(controls.categoryListContainer).find('a').live('click', function(){
		self.moving(controls.categoryListContainer, 'cat');
	    });
	    $(controls.detailsContainer).find('a').live('click', function(){
		self.moving(controls.detailsContainer, 'det');
	    });
	}*/
	self.scrollEvents('category-list-container');
    }
    this.moving = function (el, what){
	var move, obj;
	el = $(el);
	if (what == 'det') {
	    move = (window.innerWidth < 767) ? ($('#marker-details-content').width()-$('#btn-expand-markers-details', '#marker-details-content').outerWidth(true)) : 440;
	    obj = {
		'marginRight': move
	    };
	} else {
	    move = (window.innerWidth < 767) ? ($('#category-list-container').width()-$('#btn-expand-markers-list', '#category-list-container').outerWidth(true)) : 141;
	    obj = {
		'marginLeft': move
	    };
	}
	if (!el.hasClass('active')) {
	    el.addClass('active');
	    move = '+=' + move + 'px';
	} else {
	    el.removeClass('active');
	    move = '-=' + move + 'px';
	}
	if (what == 'det') {
	    obj = {
		'marginRight': move
	    };
	} else {
	    obj = {
		'marginLeft': move
	    };
	}
	el.animate(obj, {
	    duration: 500,
	    step: function() {
		google.maps.event.trigger(appMap.map, 'resize');
	    }
	});
    }
    this.scrollEvents = function (container){
	var self = this
	if (!!$('#' + container + '.overflow').length) {
	    var myScroll;
	    function loaded() {
		myScroll = new iScroll(container);
		if (!!myScroll.vScrollbarWrapper) {
		    myScroll.vScrollbarWrapper.setAttribute('class', 'scrollbar');
		}
	    }
	    /*document.addEventListener('touchmove', function (e) {
		e.preventDefault();
	    }, false);*/
            if(getInternetExplorerVersion() != '-1' && getInternetExplorerVersion() <= '8') {
                document.attachEvent('touchmove,', function (e) {
                    e.preventDefault();
                }, false);
                document.attachEvent('DOMContentLoaded', loaded, false);
            } 

            else {
                document.addEventListener('touchmove', function (e) {
                    e.preventDefault();
                }, false);
                document.addEventListener('DOMContentLoaded', loaded, false);
            }
	    loaded();
	} else {
	    setTimeout(function () {
		self.scrollEvents(container)
	    }, 1000)
	}
    },
    this.createItems = function () {
	var btns = '', active = '', i;
	///for (var i in appCategories.list) {
        for (var n=0, l=INIT.length; n<l; n++) {
            i = INIT[n];
            active = (!n)?' active':'';
		btns += '\
                    <li class="list-item '+appCategories.list[i]['categoria']+'-item">\
                        <span class="border-width bg-color-'+appCategories.list[i]['categoria']+'"></span>\
                        <a class="link'+active+'" href="'+appCategories.list[i]['categoria']+'" title="Puntos de reciclado de '+appCategories.list[i]['texto']+'" id="categoria'+appCategories.list[i]['id']+'" onclick="bindItem(this);return false;">\
                            <span class="text">'+appCategories.list[i]['texto']+'</span>\
                        </a>\
                    </li>\
                ';
	}
	return btns;
    }
}
//FIN SLIDER BOX

//INFOBOX
function InfoboxManager () {
    this.defs = {
	tpl:document.getElementById('infoboxContent')
    }
    this.options = {
	content: '',
	disableAutoPan: true,
	maxWidth: 0,
	pixelOffset: new google.maps.Size(15, -60),
	zIndex: null,
	closeBoxURL: '',
	infoBoxClearance: new google.maps.Size(1, 1),
	isHidden: false,
	pane: 'floatPane',
	enableEventPropagation: false
    }
    this.createInfoboxHtml = function (marker) {
	var content = this.defs.tpl.value.replace(/\$\{markerNombre\}/g, marker.nombre)
	.replace(/\$\{markerDireccion\}/g, marker.direccion)
	.replace(/\$\{markerImagen\}/g, marker.imagen)
	.replace(/\$\{categoriasToString\}/g, marker.categoriasToString)
	.replace(/\$\{[a-zA-Z]+\}/g, '')
	;
	var container = document.createElement('div');
	container.className = 'infobox';
	var target = document.createElement('div');
	target.className = 'target';
	container.innerHTML = content;
	container.appendChild(target);
	return {
	    container:container,
	    target:target
	}
    },
    this.bindMarker = function (mapa, marker) {
	var self = this;
	var infobox = new InfoBox(self.options);
	var infoboxHtml = self.createInfoboxHtml(marker);
	infobox.setContent(infoboxHtml.container);
	marker.infobox = infobox;
	google.maps.event.addListener(marker, "mouseover", function (e) {
	    if (self.currentInfobox != undefined) self.currentInfobox.close();
	    marker.infobox.open(mapa, marker);
	    self.currentInfobox = marker.infobox;
	})
	google.maps.event.addListener(marker, "mouseout", function (e) {
	    marker.infobox.close()
	});
    }
}

function bindItem (self) {
    if ($(self).hasClass('active')) {
	$(self).removeClass('active');
    } else {
	$(self).addClass('active');
    }
    if ($(self).hasClass('active')) {
	appMakersManager.mostrarMarkers($(self).attr('id').slice(9));
    } else {
	appMakersManager.ocultarMarkers($(self).attr('id').slice(9));
    }
}

var resizeWindow = function(){
    var w = $(window), ww, b = $('body');

    w.resize(function(){
	mqClass();
    });

    function mqClass(){
	ww = $(window).width();

	if (ww <= 480) {
	    b.addClass('mq1200 mq979 mq767 mq480');
	} else if (ww <= 767) {
	    b.removeClass('mq480').addClass('mq1200 mq979 mq767');
	} else if (ww <= 979) {
	    b.removeClass('mq767 mq480').addClass('mq1200 mq979');
	} else if (ww <= 1200) {
	    b.removeClass('mq979 mq767 mq480').addClass('mq1200');
	}
    }
    mqClass();
};

window.onload = resizeWindow;

function getInternetExplorerVersion() {
   var rv = -1;
   if (navigator.appName == 'Microsoft Internet Explorer')
   {
      var ua = navigator.userAgent;
      var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
      if (re.exec(ua) != null)
         rv = parseFloat( RegExp.$1 );
   }
   return rv;
}